package com.lc.rocketmq.config;

import com.lc.rocketmq.common.Constants;
import com.lc.rocketmq.dao.GoodsDao;
import com.lc.rocketmq.po.Goods;
import com.lc.rocketmq.service.RedisService;
import com.lc.rocketmq.service.SeckillService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuc
 * @date 2021/8/21
 * @description
 **/
@Configuration
public class GoodsConfig implements InitializingBean {

    //本地缓存记录原始库存
    private final Map<Long,Integer> goodsStock = new HashMap<>();

    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SeckillService seckillService;

    @Override
    public void afterPropertiesSet() throws Exception {
        //将库存放入redis中
        List<Goods> goods = goodsDao.findAll();
        for (Goods good : goods) {
            if(good.getStock() > 0){
                goodsStock.put(good.getId(),good.getStock());
                redisService.set(Constants.GOODS_PREFIX+good.getId(),String.valueOf(good.getStock()),-1);
                seckillService.fillStockMap(good.getId());
            }
        }
    }

    //获取原始的库存信息
    public int getOriginStock(Long id){
        Integer stock = goodsStock.get(id);
        return stock == null ? -1 : stock;
    }
}
